package com.game.connection.server;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

import com.game.connection.message.Message;

/**
 * 
 */

/**
 * @author gustavo
 * 
 */
public class ServerPlayerSender implements Runnable {

	private PrintWriter out;

	private Integer playerId;

	private HashMap<Integer, List<Message>> messages;

	public ServerPlayerSender(Integer id, OutputStream outPutStream,
			HashMap<Integer, List<Message>> message) {

		playerId = id;
		messages = message;
		this.out = new PrintWriter(outPutStream, true);

	}

	public void send() {
		// System.out.println(playerId);

		int index = messages.get(playerId).size() - 1;
		if (index > -1) {
			if (messages.get(playerId) != null) {
				while (messages.get(playerId).size() > 0) {
					Message msg = messages.get(playerId).remove(0);
					msg.setId(playerId);
					out.println(msg.write());
					System.out.println("ServerSender::" + playerId + ":::"
							+ index + "::" + msg.getTxt());
					System.out.println("ServerSender::" + playerId + ":::"
							+ index + "::" + msg.write());
				}
			}
		}

	}

	@Override
	public void run() {
		while (true) {

			send();
			try {
				// System.out.println("Teste Sender server");
				synchronized (this.messages) {
					this.messages.wait();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
